# -*- coding: utf-8 -*-
from .models import DNSs
import requests
import dns.resolver
import json


def get_msg(ip):
    url = "http://whois.pconline.com.cn/ipJson.jsp?ip=" + ip + "&json=true"
    req = requests.get(url)
    msg = req.json()
    # pro = msg['pro']
    # proCode = msg['pro']
    # city = msg['city']
    # cityCode = msg['cityCode']
    addr = msg['addr']
    err = msg['err']
    if err == "noprovince":
        return 0
    elif ckeck_ip(ip) == False:
        return 2
    else:
        add = DNSs(ip=ip, addr=addr)
        add.save()
        return 1


def ckeck_ip(ip):
    result = DNSs.objects.filter(ip=ip)
    if len(result) != 0:
        return False
    else:
        return True


def get_addr():
    msgs = DNSs.objects.all().values_list('id', 'addr')
    msg_list = []
    for msg in msgs:
        id = msg[0]
        addr = msg[1]
        msg = {
            "id": id,
            "addr": addr
        }
        msg_list.append(msg)
    # print(msg_list)
    return msg_list


def get_dns_msg(dns_id, domain_name, dns_type):
    dns_ip = DNSs.objects.get(id=dns_id).ip
    IPs = []
    ttls = []
    try:
        my_resolver = dns.resolver.Resolver()
        my_resolver.nameservers = [dns_ip]
        if dns_type == "A":
            A = my_resolver.query(domain_name, 'A')
            for ipval in A.response.answer[-1]:
                ttl = str(A.response.answer[-1].ttl)
                IP = ipval.to_text()
                IPs.append(IP)
                ttls.append(ttl)
        elif dns_type == "CNAME":
            result = dns.resolver.query(domain_name, 'CNAME')
            for i in result.response.answer:
                for j in i.items:
                    domain = j.to_text()
                    ttl = str(i.ttl)
                    IPs.append(domain)
                    ttls.append(ttl)
        IPs = "<br>".join(IPs)
        ttls = "<br>".join(ttls)
        IP_msgs = {
            "IPs": IPs,
            "ttls": ttls
        }
    except Exception as e:
        print(e)
        IP_msgs = {
            "IPs": "域名不存在！",
            "ttls": ""
        }
    return IP_msgs


if __name__ == '__main__':
    get_addr()
